<?php
/**
 * AuthController
 * 
 * @author
 * @version 
 */
//require_once 'Zend/Controller/Action.php';
class AuthController extends Zend_Controller_Action
{
    protected $_localeString;
    public function init ()
    {
        
        $this->_helper->acl->allow(null);
        //$this->_localeString = Zend_Registry::get('localeString');
    	/*
		$ajaxContenxt = $this->_helper->getHelper ( 'AjaxContext' );
		$ajaxContenxt->initContext ();
		
		$flashMessenger = $this->_helper->FlashMessenger;
		$flashMessenger->setNamespace ( 'actionErrors' );
		$this->view->actionErrors = $flashMessenger->getMessages ();
		*/
    }
    public function indexAction ()
    {
        if (null === Zend_Auth::getInstance()->getIdentity()) {
            $this->_forward('login');
        }
    }
    public function privilegesAction ()
    {
        $this->_forward('login');
    }
    public function logoutAction ()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $redirector = $this->_helper->redirector; /* @var $redirector Zend_Controller_Action_Helper_Redirector */
        $redirector->gotoRouteAndExit(array('lang' => $this->_localeString), null, true);
    }
    public function loginAction ()
    {
        $this->view->title = 'login page';
        //use action helper FormLoader to load login form
        $this->view->loginForm = $this->_helper->formLoader('login');
        if (($this->getRequest()->isXmlHttpRequest()) || ($this->getRequest()->isPost())) {
            // collect the data from the user
            $formData = $this->_getFormData();
            if (empty($formData['username'])) {
                return $this->view->result = $this->_flashMessage('Please provide a username.');
            }
            if (empty($formData['password'])) {
                return $this->view->result = $this->_flashMessage('Please provide a password.');
            } else {
                // do the authentication
                $authAdapter = $this->_getAuthAdapter($formData);
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if (! $result->isValid()) {
                    return $this->view->result = $this->_flashMessage('Login Failed');
                } else {
                    // success: store database row to auth's storage 
                    // (Not the password though!)
                    $data = $authAdapter->getResultRowObject(null, 'password');
                    $auth->getStorage()->write($data);
                    $this->view->result = $this->_flashMessage('Login Successful');
                    $this->_redirect('/');
                }
            }
        }
    }
    /********************************************************************/
    /*
   ** @author:charles
   */
    public function registerAction ()
    {
        if ($this->getRequest()->isPost()) {
            // collect the data from the user
            $formData = $this->_getFormData();
            if (empty($formData['username']) || empty($formData['password'])) {
                $this->_flashMessage('Please provide a username and password.');
            } else {
                // do the authentication
                $authAdapter = $this->_getAuthAdapter($formData);
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                //does user already exist?
                if ($result->isValid()) {
                    return $this->_flashMessage('User already exists.  Please try again.');
                } else {
                    //get db
                    $registry = Zend_Registry::getInstance();
                    $db = $registry->db;
                    //insert new user
                    $request = $this->getRequest();
                    $data = array('first_name' => $request->getParam('first_name') , 'last_name' => $request->getParam('last_name') , 'username' => $request->getParam('username') , 'password' => md5($request->getParam('password')));
                    $db->insert('users', $data);
                    $this->view->assign('title', 'Registration Process');
                    $this->view->assign('description', 'Registration success');
                    $this->_redirect('/auth/account');
                    //return;
                }
            }
        }
        //return $this->_redirect('/auth/account');
    }
    public function accountAction ()
    {
        $objUser = new User_Model_User();
    }
    /********************************************************************/
    /********************************************************************/
    protected function _flashMessage ($message)
    {
        $flashMessenger = $this->_helper->FlashMessenger;
        $flashMessenger->setNamespace('actionErrors');
        $flashMessenger->addMessage($message);
    }
    /**
     * Retrieve the login form data from _POST
     *
     * @return array
     */
    protected function _getFormData ()
    {
        $data = array();
        $filterChain = new Zend_Filter();
        $filterChain->addFilter(new Zend_Filter_StripTags());
        $filterChain->addFilter(new Zend_Filter_StringTrim());
        $data['username'] = $filterChain->filter($this->getRequest()->getPost('username'));
        $data['password'] = $filterChain->filter($this->getRequest()->getPost('password'));
        return $data;
    }
    /**
     * Set up the auth adapater for interaction with the database
     *
     * @return Zend_Auth_Adapter_DbTable
     */
    protected function _getAuthAdapter ($formData)
    {
        // db initialized in My_Plugin_Initializer
        $dbAdapter = Zend_Registry::get('db');
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
        $authAdapter->setTableName('users')->setIdentityColumn('username')->setCredentialColumn('password')->setCredentialTreatment('MD5(?)');
        // get "salt" for better security
        $registry = Zend_Registry::getInstance();
        $salt = $registry->auth->salt;
        $password = $salt . $formData['password'];
        $authAdapter->setIdentity($formData['username']);
        $authAdapter->setCredential(($password));
        return $authAdapter;
    }
}

